<!--  -->
<template>
<div class='content'>
  <van-popup v-model="timeShow"  position="bottom" round :style="{ height: '52%' }" @close="closeTime" >
    <div class="time-main">
      <div class="time-head flex-a-c flex-j-sb">
        <h3>请选择</h3>
        <div class="close flex-a-c flex-j-c" @click.stop="closeTime">
          <span class="icon-icon_close iconfont"></span>
        </div>
      </div>
      <div class="time-content">
        <div class="time-list flex">
          <div class="time-item" 
            v-for="(item,index) in timeList" 
            :key="index" 
            @click="timeSelect(item,index)" 
            :class="index == timeIndex?'on':''" 
            :style="index == timeIndex?`background:rgba(${coThemeColor},0.1)`:''" >{{item.name}}</div>
        </div>
        <h3 class="title">自定义日期</h3>
        <div class="custom-time flex-a-c">
          <div class="custom-btn" @click.stop="customTimeOn('start')">{{startTimeName}}</div>
          <div class="custom-icon"></div>
          <div class="custom-btn" @click.stop="customTimeOn('end')">{{endTimeName}}</div>
        </div>
        <!-- <div class="mh-88"></div> -->
        <div  class="account-btn custom-shadow"  :style="iPnoneBottomBol ? 'padding-bottom: 34px;' : ''">
          <van-button round block type="info"  color="var(--themeBaseColor)" @click="timeConfirm">确定</van-button>
        </div>
      </div>
    </div>
  </van-popup>
  <van-popup v-model="dateShow" position="bottom" :style="{ height: '50%' }" round>
    <van-datetime-picker
      v-model="currentDate"
      type="date"
      :title="timeType == 'start'?'开始日期':'截止日期'"
      :min-date="minDate"
      :max-date="maxDate"
      @cancel="dateCancel"
      @confirm="dateConfirm"
      :formatter="formatter"
    />
  </van-popup>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
name:'',
//import引入的组件需要注入到对象中才能使用
components: {},
props:{
  timeList:{
    type:Array,
    default(){
      return []
    }
  },
  coThemeColor:{
    type:String,
    default:'241, 83, 83'
  },
  timeIndex:Number,
  timeShow:Boolean
},
data() {
return {
  dateShow:false,
  minDate: new Date(2000, 0, 1),
  maxDate: new Date(2050, 10, 1),
  currentDate: new Date(),
  endTime:'',
  startTime:'',
  timeType:'',
  startTimeName:'开始时间',
  endTimeName:'结束时间',
  timeName:'',
  result:[], //处理时间的结果
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
  timeSelect(item,index) {
    const today = new Date();
    const yesterday = new Date(today); //今天
    const dayOfWeek = today.getDay(); // 获取今天是星期几（0表示星期日，6表示星期六）
    let result = [];
    let yesterdayStart = '';
    let twoDaysAgoEnd = '';  
    // yesterday.setDate(today.getDate());  
    let yesterdayTime = new Date(today); //昨天
    const twoDaysAgo = new Date(today);  
    twoDaysAgo.setDate(today.getDate() - 2);  //最近三天
    yesterdayTime.setDate(today.getDate() - 1);
    if(item.value == 0) {
      this.result = [];
     
    } else if (item.value == 1) {
      yesterdayStart = this.getStartOfDayTimestamp(twoDaysAgo); 
      twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterday); 
    } else if (item.value == 2) {
      yesterdayStart = this.getStartOfDayTimestamp(yesterday)
      twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterday); 
    } else if (item.value == 3) {
      yesterdayStart = this.getStartOfDayTimestamp(yesterdayTime)
      twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterdayTime);
    } else  if (item.value == 4) { 
      //  this.lastWeek();
      const dateRangeTimestamps = this.getTimestamps();
      yesterdayStart = dateRangeTimestamps.startOfPreviousWeek;
      twoDaysAgoEnd =  dateRangeTimestamps.endOfPreviousWeek;
    } else if (item.value == 5) {
      // 计算这一周的结束日期（星期日） 
      let startOfPreviousWeek = new Date(today);  
      startOfPreviousWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)); 
      let endOfPreviousWeek = new Date(startOfPreviousWeek);  
      endOfPreviousWeek.setDate(startOfPreviousWeek.getDate() + 6);
      yesterdayStart = this.getStartOfDayTimestamp(startOfPreviousWeek)
      twoDaysAgoEnd = this.getEndOfDayTimestamp(endOfPreviousWeek); 
    } else if (item.value == 6) {
      //上一月的时间戳
      const dateTimestamps = this.getLastMonth();
      yesterdayStart = dateTimestamps.startOfPreviousMonth;
      twoDaysAgoEnd =  dateTimestamps.endOfPreviousMonth;
    }else if (item.value == 7) {
      //本月的时间戳
      const dateTimeMonth = this.getCurrentMonth();
      yesterdayStart = dateTimeMonth.startOfCurrentMonth;
      twoDaysAgoEnd =  dateTimeMonth.endOfCurrentMonth;
    } else {
      this.$toast('错误错误错误');
    }
    this.timeName = item.name;
    result.push(yesterdayStart)
    result.push(twoDaysAgoEnd)
    console.log(result);
    this.result = result;
    // this.timeIndex = index;
    // if()
    this.$emit('timeSelect',{item:item,index:index});
  },
  //c
  getTimestamps() {  
      const now = new Date();  
      const dayOfWeek = now.getDay(); // 获取今天是星期几（0表示星期日，6表示星期六）  
      // 计算上一周的起始日期（星期一）的00:00:00  
      let startOfPreviousWeek = new Date(now);  
      startOfPreviousWeek.setDate(now.getDate() - dayOfWeek - (dayOfWeek === 0 ? 0 : 7) + 1);  
      startOfPreviousWeek.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
    
      // 计算上一周的结束日期（星期日）的23:59:59  
      // 由于我们已经有了上一周的星期一，所以直接加6天即可得到上一周的星期日  
      let endOfPreviousWeek = new Date(startOfPreviousWeek);  
      endOfPreviousWeek.setDate(startOfPreviousWeek.getDate() + 6);  
      endOfPreviousWeek.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
    
      // 验证结束日期确实在上一周（有时由于月份或年份变更，简单加6天可能不正确）  
      // 但在这个特定情况下，由于我们已经从星期一开始加6天到星期日，所以不需要额外验证  
    
      // 返回时间戳  
      return {  
          startOfPreviousWeek: startOfPreviousWeek.getTime(),  
          endOfPreviousWeek: endOfPreviousWeek.getTime()  
      };  
  },
  getLastMonth() {  
      const now = new Date();  
      const currentMonth = now.getMonth();  
      const currentYear = now.getFullYear();  
    
      // 计算上一个月  
      let previousMonth = currentMonth - 1;  
      let previousYear = currentYear;  
    
      // 处理上一个月是上一年的情况  
      if (previousMonth < 0) {  
          previousMonth = 11;  
          previousYear -= 1;  
      }  
    
      // 计算上一个月的第一天  
      let startOfPreviousMonth = new Date(previousYear, previousMonth, 1);  
      startOfPreviousMonth.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
    
      // 计算上一个月有多少天  
      let daysInPreviousMonth = new Date(previousYear, previousMonth + 1, 0).getDate();  
    
      // 计算上一个月的最后一天  
      let endOfPreviousMonth = new Date(previousYear, previousMonth, daysInPreviousMonth);  
      endOfPreviousMonth.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
    
      // 返回时间戳  
      return {  
          startOfPreviousMonth: startOfPreviousMonth.getTime(),  
          endOfPreviousMonth: endOfPreviousMonth.getTime()  
      };  
  },
  getCurrentMonth() {  
      const now = new Date();  
      const currentMonth = now.getMonth();  
      const currentYear = now.getFullYear();  
    
      // 计算本月的第一天  
      let startOfCurrentMonth = new Date(currentYear, currentMonth, 1);  
      startOfCurrentMonth.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
    
      // 计算本月有多少天  
      let daysInCurrentMonth = new Date(currentYear, currentMonth + 1, 0).getDate();  
    
      // 计算本月的最后一天  
      let endOfCurrentMonth = new Date(currentYear, currentMonth, daysInCurrentMonth);  
      endOfCurrentMonth.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
    
      // 返回时间戳  
      return {  
          startOfCurrentMonth: startOfCurrentMonth.getTime(),  
          endOfCurrentMonth: endOfCurrentMonth.getTime()  
      };  
  },
  // 辅助函数：获取指定日期的00:00:00时间戳  
  getStartOfDayTimestamp(date) {  
      const startOfDay = new Date(date);  
      startOfDay.setHours(0, 0, 0, 0);  
      return startOfDay.getTime();  
  },
  // 辅助函数：获取指定日期的23:59:59时间戳  
  getEndOfDayTimestamp(date) {  
      const endOfDay = new Date(date);  
      endOfDay.setHours(23, 59, 59, 999); // 毫秒设为999以确保是当天的最后一毫秒  
      return endOfDay.getTime();  
  },
  dateCancel() {
    if(this.timeType == 'start') {
      this.startTimeName ='开始时间';
      this.startTime = '';
    } else {
      this.endTimeName = '结束时间';
      this.endTime = '';
    }
    this.dateShow = false;
  },
  timeConfirm() {
    this.$emit('update:timeShow',false);
    let result = [];
    
    result.push(this.startTime)
    result.push(this.endTime)
    if(this.result.length == 0) {
      this.result = result;
    }
    this.$emit('timeConfirm',{result:this.result,timeName:this.timeName});
  },
  closeTime() {
    this.$emit('update:timeShow',false);
  },
  customTimeOn(name) {
    this.timeType = name;
    this.dateShow = true;
  },
  formatter(type, val) {
    if (type === 'year') {
      return val + '年';
    }
    if (type === 'month') {
      return val + '月';
    }
    if (type === 'day') {
      return val + '日';
    }
    return val;
  },
  dateConfirm(event) {
    this.result = [];
    this.timeName = '全部时间';
    if(this.timeType == 'start') {
      this.startTimeName = this.timestampToTime(Date.parse(event));
      this.startTime = Date.parse(event);
    } else {
      this.endTimeName = this.timestampToTime(Date.parse(event));
      this.endTime = Date.parse(event);
    }
    this.dateShow = false;
  },
  //将时间戳转换成正常时间格式
  timestampToTime: function(timestamp, key) {
    if (!Number(timestamp) || timestamp == "") {
      return "";
    }
    let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "-";
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
    let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return Y + M + D;
  }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {

},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入公共css类 */
.pcStyle .account-btn {
  position: fixed;
  width: 23.4375rem;
  left:50%;
  bottom: 0;
  transform: translate(-50%, 0%);
  margin: 0 auto;
}
.time-main {
  padding:1.25rem 0.75rem 2.1875rem 0.75rem;
  .time-head {
    padding:0 0 1rem 0;
    h3 {
      font-weight: bold;
      font-size: 1rem;
      color: #00001C;
    }
    .close {
      width: 1.5rem;
      height: 1.5rem;
      background: #F0F0F1;
      border-radius: 50%;
      .icon-icon_close {
        font-size: 0.875rem;
      }
    }
  }
  .time-content {
    .time-list {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        column-gap: 0.625rem;
        row-gap: 0.625rem;
      .time-item {
        min-width: 4.9375rem;
        box-sizing: border-box;
        background: #F5F5F5;
        border-radius: 1rem 1rem 1rem 1rem;
        padding:0.5625rem 0.875rem;
        font-weight: 400;
        font-size: 0.875rem;
        line-height: 0.875rem;
        color: #00001C;
      }
      .on {
        border: 0.0625rem solid var(--themeBaseColor);
        color:var(--themeBaseColor);
        // background-color: rgba(241, 83, 83, 0.10);
      }
    }
    
  }
  .title {
    text-align: left;
    padding:1.25rem 0 0.9375rem 0;
  }
  .custom-time {
    .custom-icon {
      width: 0.625rem;
      height: 0.0625rem;
      background: #999999;
      margin:0 0.5rem;
    }
    .custom-btn {
      width: 10rem;
      text-align: center;
      height: 2rem;
      line-height: 2rem;
      background: #F5F5F5;
      border-radius: 1rem 1rem 1rem 1rem;
    }
    
  }
  .custom-shadow {
    box-shadow: 0rem 0 0.3125rem 0.0625rem #F5F5F5;
  }
  .account-btn {
    width:100%;
    background-color: #fff;
    position: fixed;
    left:0;
    bottom:0;
    padding:0.625rem 0.75rem;
  }
}
</style>